package multi_ponit;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MutiPoint {
	
	private String filename;
	private ExecutorService executorService;
	
	private RandomAccessFile randomAccessFile;
	
	private long length;
	
	private String toFileName;
	
	
	
	public MutiPoint(String filename){
		this.filename = filename;
		executorService = Executors.newCachedThreadPool();
	}
	
	
	public String preLoad(){
		
		File file = new File(filename);
		if (!file.exists()) {
			return "file no exists";
		}
		length = file.length();
		String[] names = filename.split("\\\\");
		String name = names[names.length-1];
		toFileName = "multipoint/"+name;
		try {
			randomAccessFile = new RandomAccessFile(toFileName, "rw");
			randomAccessFile.setLength(length);
			return "success";
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return "fail";
	}
	
	public void load(){
		long len = length/5;
		int count = 0;
		for (; count <4; count++) {
			FileDownloadImpl fileDownloadImpl = new FileDownloadImpl(filename, toFileName, count*len, (count+1)*len);
			executorService.execute(fileDownloadImpl);
		}
		executorService.execute(new FileDownloadImpl(filename, toFileName, count*len, length));
		
	}
	
	
	public String verify(){
		executorService.shutdown();
		while (true) {
			if(executorService.isTerminated()){
				return "success";
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
